package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

public class Devoluciones extends javax.swing.JInternalFrame {
    private String id_bitacora;
    private JFileChooser selector;
    public Devoluciones() {
        initComponents();
        this.setLocation(new Point(70, 0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("devoluciones.xls"));
        this.jpObservacion.setVisible(false);
        jbtnGuardar.setEnabled(false);
        jbtnCancelar.setEnabled(false);
        Util.CargarJComboBox(jcbBodega, "SELECT id_bodega,nombre FROM bodega", new String[]{"id", "descripcion"});
        Util.OcultarColumna(jtblDatosDevolucion, 0);
        Util.OcultarColumna(jtblDatosDevolucion, 2);
        Util.EstablecerEliminadorFila(jtblDatosDevolucion);
        if(Conexion.bitacora) id_bitacora=Util.IniciarBitacora(this.getTitle());
    }
    private void Limpiar() {
        jtfSolicitante.setText("");
        jtfFechaSolicitud.setText("");
        jtaObservacion.setText("");
        jcbBodega.setSelectedIndex(-1);
        ((MyModeloTablaEditable) jtblDevolucion.getModel()).EliminarFilas();
        while(jtblDatosDevolucion.getRowCount()>0)
            ((DefaultTableModel)jtblDatosDevolucion.getModel()).removeRow(0);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfCodigoSolicitud = new javax.swing.JTextField();
        jbtnBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblDatosDevolucion = new javax.swing.JTable();
        jpAccion = new javax.swing.JPanel();
        jbtnCancelar = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();
        jbtnExportar = new javax.swing.JButton();
        jlSolicitante = new javax.swing.JLabel();
        jtfSolicitante = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfFechaSolicitud = new javax.swing.JTextField();
        jpObservacion = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtaObservacion = new javax.swing.JTextArea();
        jlSolicitante1 = new javax.swing.JLabel();
        jcbBodega = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jbtnAgregar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtblDevolucion = new javax.swing.JTable();

        setClosable(true);
        setMaximizable(true);
        setTitle("Devolución de Producto");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/devolucion.png"))); // NOI18N
        setVisible(false);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jLabel1.setText("Código de Solicitud:");

        jtfCodigoSolicitud.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfCodigoSolicitudKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfCodigoSolicitudKeyTyped(evt);
            }
        });

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar_mini.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jtblDatosDevolucion.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id_inventario", "Producto", "id_bodega", "Bodega", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.Long.class, java.lang.String.class, java.lang.Long.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtblDatosDevolucion);

        jpAccion.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));

        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_cancelar.png"))); // NOI18N
        jbtnCancelar.setToolTipText("Cancelar");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpAccionLayout = new javax.swing.GroupLayout(jpAccion);
        jpAccion.setLayout(jpAccionLayout);
        jpAccionLayout.setHorizontalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpAccionLayout.createSequentialGroup()
                .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jpAccionLayout.setVerticalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jlSolicitante.setText("Solicitante:");

        jtfSolicitante.setEditable(false);

        jLabel2.setText("Fecha de Solicitud:");

        jtfFechaSolicitud.setEditable(false);

        jtaObservacion.setEditable(false);
        jtaObservacion.setColumns(20);
        jtaObservacion.setRows(5);
        jScrollPane2.setViewportView(jtaObservacion);

        jlSolicitante1.setText("Observación:");

        javax.swing.GroupLayout jpObservacionLayout = new javax.swing.GroupLayout(jpObservacion);
        jpObservacion.setLayout(jpObservacionLayout);
        jpObservacionLayout.setHorizontalGroup(
            jpObservacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpObservacionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlSolicitante1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 530, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(64, 64, 64))
        );
        jpObservacionLayout.setVerticalGroup(
            jpObservacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpObservacionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlSolicitante1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jpObservacionLayout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jcbBodega.setToolTipText("Bodega donde se Devolvera el Producto");

        jLabel3.setText("Bodega:");

        jbtnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_nuevo.png"))); // NOI18N
        jbtnAgregar.setToolTipText("Agregar");
        jbtnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAgregarActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(jtblDevolucion);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(249, 249, 249)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcbBodega, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jpObservacion, javax.swing.GroupLayout.PREFERRED_SIZE, 615, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfFechaSolicitud))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfCodigoSolicitud, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jlSolicitante)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfSolicitante, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                        .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane3))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jlSolicitante)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel1)
                                    .addComponent(jtfCodigoSolicitud)))
                            .addComponent(jtfSolicitante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jtfFechaSolicitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpObservacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jcbBodega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(51, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        if (!jtfCodigoSolicitud.getText().equals("")) {
            Buscar(jtfCodigoSolicitud.getText());
        } else {
            JOptionPane.showMessageDialog(null, "Debe ingresar un código de solicitud.", "Falta Código de Solicitud", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void Buscar(String devolucion) {
        Util.CargarTablaEditable(jtblDevolucion, "CALL VerDevolucion(" + devolucion + ")",
                new String[]{"id", "Nombre", "Unidad de Medida", "Detalle", "Prestado", "Devuelto", "Cantidad a Devolver", "Pendiente"},
                new boolean[]{false, false, false, false, false, false, true, false});
        Util.OcultarColumna(jtblDevolucion, 0);
        for (int i = 0; i < jtblDevolucion.getRowCount(); i++) {
            int prestado = new Integer(jtblDevolucion.getValueAt(i, 4).toString());
            int devuelto = new Integer(jtblDevolucion.getValueAt(i, 5).toString());
            jtblDevolucion.setValueAt(prestado - devuelto, i, 7);
        }
        JTable tabla = Conexion.ObtenerTabla("SELECT CONCAT_WS(' ',se.nombres,se.apellidos) AS nombre,DATE_FORMAT(sd.fecha,'%d/%m/%Y') AS fecha,sd.observacion FROM solicitud sd INNER JOIN solicitante se ON sd.id_solicitante=se.id_solicitante WHERE sd.id_solicitud=" + devolucion, new String[]{"nombre", "fecha", "observacion"});
        if (tabla.getRowCount() > 0) {
            jtfSolicitante.setText(tabla.getValueAt(0, 0).toString());
            jtfFechaSolicitud.setText(tabla.getValueAt(0, 1).toString());
            String obs = tabla.getValueAt(0, 2).toString();
            jtaObservacion.setText((obs.length() > 0 ? obs : ""));
            this.jpObservacion.setVisible(!jtaObservacion.getText().equals(""));
            jbtnGuardar.setEnabled(true);
            jbtnCancelar.setEnabled(true);
        }
    }
    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        jbtnGuardar.setEnabled(false);
        jbtnCancelar.setEnabled(false);
        jtfCodigoSolicitud.setText("");
        jtfFechaSolicitud.setText("");
        jtaObservacion.setText("");
        jpObservacion.setVisible(false);
        Limpiar();
    }//GEN-LAST:event_jbtnCancelarActionPerformed
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        if(jtblDatosDevolucion.getRowCount()>0)
            Guardar();
        else
            JOptionPane.showMessageDialog(null,"Deben haber por lo menos un producto de inventario para poder realizar la devolución","No hay productos para devolver",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private void Guardar() {
        SimpleDateFormat formato = new SimpleDateFormat("yyyy/MM/dd");
        String detalle[]=SumatoriaDevolucion();
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL AgregarDevolucion("+jtfCodigoSolicitud.getText()+",'"+formato.format(new Date())
                +"','"+detalle[0]+"','"+detalle[1]+"','"+detalle[2]+"');")){
                        if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Guardar Devolución: "+Util.ComponerTexto(jtfCodigoSolicitud.getText()+" - "+jtfSolicitante.getText()));
                        Limpiar();
                        JOptionPane.showMessageDialog(null,"Devolución Realizada","Devolución de Producto",JOptionPane.INFORMATION_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(null,"No se pudo realizar la de devolución.","Devolución de Producto",JOptionPane.WARNING_MESSAGE);
            
    }
    private String[] SumatoriaDevolucion() {
        String detalle[] = {"", "", ""};
        ArrayList<detalledevolucion> lista = new ArrayList<detalledevolucion>();
        for (int i = 0; i < jtblDatosDevolucion.getRowCount(); i++) {
            int inventario = new Integer(jtblDatosDevolucion.getValueAt(i, 0).toString());
            int bodega = new Integer(jtblDatosDevolucion.getValueAt(i, 2).toString());
            int cantidad = new Integer(jtblDatosDevolucion.getValueAt(i, 4).toString());
            lista.add(new detalledevolucion(inventario, bodega, cantidad));
        }
        for (int i = 0; i < lista.size(); i++) {
            if (i == lista.size() - 1) {
                detalle[0] += lista.get(i).inventario;
                detalle[1] += lista.get(i).bodega;
                detalle[2] += lista.get(i).cantidad;
            } else {
                detalle[0] += lista.get(i).inventario + ",";
                detalle[1] += lista.get(i).bodega + ",";
                detalle[2] += lista.get(i).cantidad + ",";
            }
        }
        return detalle;
    }

    private class detalledevolucion {

        public int inventario, bodega, cantidad;

        public detalledevolucion(int inventario, int bodega, int cantidad) {
            this.inventario = inventario;
            this.bodega = bodega;
            this.cantidad = cantidad;
        }
    }
    private void AgregarProductoDevolucion(int fila){
        int inventario,id_inventario,bodega;
        id_inventario=new Integer(jtblDevolucion.getValueAt(fila,0).toString());
        ModeloItemValor id_bodega = (ModeloItemValor)jcbBodega.getSelectedItem();
        for(int i=0;i<jtblDatosDevolucion.getRowCount();i++){
            inventario=new Integer(jtblDatosDevolucion.getValueAt(i,0).toString());
            bodega=new Integer(jtblDatosDevolucion.getValueAt(i,2).toString());
            if(id_inventario==inventario && new Integer(id_bodega.getValor())==bodega){
                jtblDatosDevolucion.setValueAt(new Integer(jtblDatosDevolucion.getValueAt(i,4).toString())+new Integer(jtblDevolucion.getValueAt(fila,6).toString()),i,4);
                return;
            }
        }
        
        String producto = jtblDevolucion.getValueAt(fila, 1).toString() + " " + jtblDevolucion.getValueAt(fila, 2).toString() + " " + jtblDevolucion.getValueAt(fila, 3).toString();
        ((DefaultTableModel)jtblDatosDevolucion.getModel()).addRow(new Object[]{id_inventario,producto,id_bodega.getValor(),id_bodega,jtblDevolucion.getValueAt(fila, 6).toString()});
    }
    private boolean Validar() {
        int fila = jtblDevolucion.getSelectedRow();
        if (fila > -1) {
            if (jcbBodega.getSelectedIndex() > -1) {
                if (new Integer(jtblDevolucion.getValueAt(fila, 6).toString()) > 0) {
                    int prestado = new Integer(jtblDevolucion.getValueAt(fila, 4).toString());
                    int devuelto = new Integer(jtblDevolucion.getValueAt(fila, 5).toString());
                    int cantidad = new Integer(jtblDevolucion.getValueAt(fila, 6).toString());
                    if (prestado - devuelto - cantidad > -1) {
                        if(VerificarCantidadProductoActual(new Integer(jtblDevolucion.getValueAt(fila,0).toString()),new Integer(jtblDevolucion.getValueAt(fila,7).toString()),cantidad))
                            return true;
                        else
                            JOptionPane.showMessageDialog(null, "La cantidad a devolver no debe superar la cantidad pendiente.\nSe toma en cuenta también la cantidad que se ingreso en la tabla inferior.", "Devoluciones", JOptionPane.WARNING_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(null, "La cantidad a devolver no debe superar la cantidad pendiente.", "Devoluciones", JOptionPane.WARNING_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "La cantidad a devolver debe ser mayor que cero.", "Devoluciones", JOptionPane.WARNING_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Debe seleccionar una bodega para agregar el producto.", "Devoluciones", JOptionPane.WARNING_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un producto para agregarlo.", "Devoluciones", JOptionPane.WARNING_MESSAGE);
        }
        return false;
    }
    private boolean VerificarCantidadProductoActual(int inventario,int pendiente,int cantidad){
        int id_inventario,cantidad_datos=0;
        for(int i=0;i<jtblDatosDevolucion.getRowCount();i++){
            id_inventario=new Integer(jtblDatosDevolucion.getValueAt(i,0).toString());
            if(id_inventario==inventario)
                cantidad_datos+=new Integer(jtblDatosDevolucion.getValueAt(i,4).toString());
        }
        return (cantidad+cantidad_datos <= pendiente);
    }
    private void jtfCodigoSolicitudKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodigoSolicitudKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (!jtfCodigoSolicitud.getText().equals("")) {
                Buscar(jtfCodigoSolicitud.getText());
            } else {
                JOptionPane.showMessageDialog(null, "Debe ingresar un código de solicitud.", "Falta Código de Solicitud", JOptionPane.WARNING_MESSAGE);
            }
        }
    }//GEN-LAST:event_jtfCodigoSolicitudKeyPressed
    private void jbtnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAgregarActionPerformed
        if (Validar()) {
            int fila=jtblDevolucion.getSelectedRow();
            int cantidad=new Integer(jtblDevolucion.getValueAt(fila,6).toString());
            if(cantidad>0){
                AgregarProductoDevolucion(fila);
                jtblDevolucion.setValueAt(0,fila,6);
            }
        }
    }//GEN-LAST:event_jbtnAgregarActionPerformed
    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized

    private void jtfCodigoSolicitudKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodigoSolicitudKeyTyped
        if(!Util.esNumero(jtfCodigoSolicitud.getText()+evt.getKeyChar(),false))
            evt.consume();
    }//GEN-LAST:event_jtfCodigoSolicitudKeyTyped
    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
    }//GEN-LAST:event_formInternalFrameClosing

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblDatosDevolucion.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarExcel(jtblDevolucion,archivo_excel,"Devolución")){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbtnAgregar;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JComboBox jcbBodega;
    private javax.swing.JLabel jlSolicitante;
    private javax.swing.JLabel jlSolicitante1;
    private javax.swing.JPanel jpAccion;
    private javax.swing.JPanel jpObservacion;
    private javax.swing.JTextArea jtaObservacion;
    private javax.swing.JTable jtblDatosDevolucion;
    private javax.swing.JTable jtblDevolucion;
    private javax.swing.JTextField jtfCodigoSolicitud;
    private javax.swing.JTextField jtfFechaSolicitud;
    private javax.swing.JTextField jtfSolicitante;
    // End of variables declaration//GEN-END:variables
}